import { defineComponent, ref, VNode } from 'vue';
/* components */
import QualityHeader from '@src/modules/intelligentQuality/views/components/qualityHeader.tsx';
import QualityTableHeader from '@src/modules/intelligentQuality/views/components/qualityTableHeader';
import BaseChange from '@src/modules/intelligentQuality/components/baseChange.tsx'
import QualityCard from '@src/modules/intelligentQuality/views/components/qualityCard.tsx'
import QualityTable from '@src/modules/intelligentQuality/views/components/qualityTable.tsx'
import CreateRobotDialog from '@src/modules/intelligentQuality/views/createQualityDialog/index.tsx'
import NoDataViewNew from '@src/component/common/NoDataViewNew';
/* scss*/
import '@src/modules/intelligentQuality/style/index.scss';
/* utils */
import { useThrottleFn } from '@vueuse/core'
import { t } from '@src/locales';
import { openAccurateTab } from '@src/util/platform'
import { message, confirm } from '@src/util/message'
import { isFalse, isFalsy } from '@src/util/type'
import { getGray } from '@src/modules/intelligentQuality/utils/index.ts'
import state from '@src/modules/intelligentQuality/utils/state.ts'
/* http */
import * as qualityApi from '@src/api/intelligentQuality.js'
/* type */
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

type changeType = 'card' | 'list'
export default defineComponent({
  name: 'intelligentRobot',
  setup() {

    const inputValue = ref('')
    const loading = ref(true)
    const toggleShow = ref<changeType>('card')
    const createRobotDialogRef = ref<any>(null)
    // 列表数据
    const qualityList = ref([])
    
    const initAuthRobot = () => {
      const authRes = getGray()
      state.auth.create =   Reflect.has(authRes.user?.auth, 'INTELLIGENT_ROBOT_CREATE')
      state.auth.edit = Reflect.has(authRes.user?.auth, 'INTELLIGENT_ROBOT_EDIT')
      state.auth.delete = Reflect.has(authRes.user?.auth, 'INTELLIGENT_ROBOT_DELETE')
    }
    initAuthRobot()

    /**
     * @description 搜索
     */
    const handleSearch = () => {
      showLoading()
      getQualityTableList()
    }

    const handleSearchFn = useThrottleFn(handleSearch, 500)
    /**
     * @description 输入搜索触发
     * @param e 
     */
    const inputKeyword = (e: string) => {
      inputValue.value = e
      handleSearchFn()
  }

    /**
     * @description 切换list和card展示模式
     * @param item 
     */
    const clickChangeStatus = (item: changeType) => {
        toggleShow.value = item
    }

    /**
     * @description 清除loading
     */
    const clearLoading = () => {
      loading.value = false
    }
    const showLoading = () => {
      loading.value = true
    }

    // 获取质检机器人列表
    const getQualityTableList = async () => {
      try {
        const res = await qualityApi.getRobotList({
          keyword: inputValue.value,
          pageNo: 1,
          pageSize: 99999
        })
        if (res.status !== 0) {
          return
        }
        qualityList.value = res.data.list
        clearLoading()
      } catch (error) {
        console.error(error)
      }
    }
    // 新建触发器弹窗显示
    const onCreateConnectorHandler = () => {
      if (!state.auth.create) {
        message.error(t('robot.text1'))
        return
      }
      createRobotDialogRef.value.showDialog()
    }

    getQualityTableList()

    /**
     * @description 删除逻辑
     */
    const handlerDelete = async (id: string) => {
      const confirmed = await confirm.warning(t('robot.text2'), t('robot.tip'))

      if (isFalsy(confirmed)) {
        return
      }
      loading.value = true
      qualityApi.deleteRobot({ robotNo: id}).then(res => {
        if (!res.success) {
          message.error(res.message)
          loading.value = false
          return
        }
        qualityList.value = qualityList.value.filter(item => item.robotNo !== id)
        message.success(t('robot.delete1'))
        loading.value = false
      })
      .catch(err => {
          message.error(err.message)
          // @ts-ignore
          console.error(err)
          loading.value = false
      })
    }
    
    /**
     * @description 编辑逻辑
     */
    const handlerEdit = (id: string) => {
      let fromId = window?.frameElement?.getAttribute('id')
      openAccurateTab({
        type: PageRoutesTypeEnum.IntelligentQualityEdit,
        params: `robotNo=${id}&isEdit=true`,
        fromId
      })
    }

    // /**
    //  * @description 切换开关按钮逻辑
    //  */
    // const handlerChange = (val: number, row: any) => {
    //   qualityApi.switchRobot({robotNo: row.robotNo, enabled: val}).then(res => {
    //     if (!res.success) {
    //       message.error(res.message)
    //       return
    //     }
    //     if (val) {
    //       message.success("启用成功")
    //     } else {
    //       message.success("停用成功")
    //     }
    //     qualityList.value = qualityList.value.map(item => {
    //       if (item.robotNo === row.robotNo) {
    //         item.enabled = val
    //       }
    //       return item
    //     })
    //   })
    //   .catch(err => {
    //     message.error(err.message)
    //   })
      
    // }

    /**
     * @description 点击跳转到详情页
     */
    const clickGoDetail = (robotNo: string) => {
      let fromId = window?.frameElement?.getAttribute('id')
      // 临时先这样
      openAccurateTab({
        type: PageRoutesTypeEnum.IntelligentQualityDetail,
        params: `robotNo=${robotNo}`,
        fromId
      })
    }


    return () => (
      <div class="int-robot">
        <QualityHeader />
        <div class="int-content">
          <div class="int-table-list">
            <QualityTableHeader>
              <div slot={'right'}>
                <div class="customer-list-base-search-group input-with-append-search">
                  <el-input
                    value={inputValue.value}
                    placeholder={t('robot.placeholder')}
                    class="mar-r-12"
                    style={{ width: '300px' }}
                    onInput={(e) => inputKeyword(e)}
                  >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    {
                      <el-button type="primary" slot="append" onClick={() => handleSearch()} native-type="submit">
                        {t('common.base.search')}
                      </el-button>
                    }
                  </el-input>
                  {/* 切换状态 */}
                  <BaseChange onChange={item => clickChangeStatus(item)} value={toggleShow.value} />
                </div>
              </div>

              <div slot={'left'}>
                <el-button type="primary" onClick={() => onCreateConnectorHandler()}>
                  {t('common.base.create')}
                </el-button>
              </div>
            </QualityTableHeader>
            <div class="int-card" v-show={toggleShow.value === 'card'}>
              {
                qualityList.value.length > 0 ? (
                  <QualityCard loading={loading.value} cardList={qualityList.value} onDelete={(id) => handlerDelete(id)} onEdit={(id) => handlerEdit(id)}  onGoDetail={(robotId) => clickGoDetail(robotId)} />
                ) : (
                  <div style="display:flex;width:100%;justify-content:center;">
                      <NoDataViewNew />
                  </div>
                )
              }
            </div>
            <div class="int-table" v-show={toggleShow.value === 'list'}>
              {
                qualityList.value.length > 0 ? (
                  <QualityTable loading={loading.value} tableList={qualityList.value} onDelete={(id) => handlerDelete(id)} onEdit={(id) => handlerEdit(id)}  onGoDetail={(robotId) => clickGoDetail(robotId)} />
                ) : (
                  <NoDataViewNew />
                )
              }
            </div>
          </div>
        </div>
        <CreateRobotDialog ref={createRobotDialogRef} />
      </div>
    ) as unknown as VNode;
  },
});
